package com.huawei.app.demo.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Locale;

/**
 * 工具类
 *
 * @since 2021-04-14
 */
public class CommonUtils {

    private static final String TAG = CommonUtils.class.getSimpleName();

    /**
     * 获取证书库第一个条目的SHA1指纹信息
     * @param keyStoreFile 证书库路径
     * @param storepass 获取证书指纹理论上不需要密码
     * @return 证书指纹信息(SHA1)
     */
    public static String getCertThumbprint(String keyStoreFile, String storepass) {
        char[] pass = null;
        if (storepass != null && !storepass.trim().isEmpty()) {
            pass = storepass.toCharArray();
        }

        String sha1 = "";
        try (FileInputStream fin = new FileInputStream(keyStoreFile)) {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(fin, pass);
            Enumeration<String> enumeration = keyStore.aliases();
            if (!enumeration.hasMoreElements()) {
                return sha1;
            }

            String alias = enumeration.nextElement();
            X509Certificate cert = (X509Certificate)keyStore.getCertificate(alias);
            sha1 = getSHA1Str(cert.getEncoded());
        } catch (GeneralSecurityException | IOException e) {
            LogUtils.getInstance().e(TAG, "getCertThumbprint failed", e);
        }
        return sha1;
    }

    /**
     * 计算SHA1摘要信息
     * @param plaindata 用于计算消息摘要的原始数据
     * @return SHA1消息摘要
     */
    public static String getSHA1Str(byte[] plaindata) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(plaindata);
            byte[] data = md.digest();
            result = toHexStr(data, ":");
        } catch (NoSuchAlgorithmException e) {
            LogUtils.getInstance().e(TAG, "getSHA1Str failed", e);
        }
        return result;
    }

    /**
     * 转换为16进制字符串
     * @param binaryBytes 二进制数据
     * @param separator 分隔符
     * @return 16进制字符串
     */
    private static String toHexStr(byte[] binaryBytes, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<binaryBytes.length; i++) {
            int v = binaryBytes[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sb.append("0");
            }
            sb.append(hv);

            if (i < binaryBytes.length - 1) {
                sb.append(separator);
            }
        }
        return sb.toString().toUpperCase(Locale.US);
    }
}
